package com.zzw.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzw.springboot.bean.Supplier;
import com.zzw.springboot.bean.SysUser;
import com.zzw.springboot.service.SupplierService;
import com.zzw.springboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 供应商控制器
 */
@Controller
@RequestMapping("/supplier")
public class SupplierController extends BaseController {

    @Autowired
    private SupplierService supplierService;

    /**
     * 查询供应商列表
     */
    @GetMapping("/list")
    @ResponseBody
    public Result listSuppliers(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             Supplier supplier) {
        //创建lambdaQueryWrapper, 封装查询条件
        LambdaQueryWrapper<Supplier> lambdaQueryWrapper = Wrappers.<Supplier>lambdaQuery();
        Page<Supplier> page = supplierService.page(new Page<Supplier>(pageNum, pageSize), lambdaQueryWrapper);
        return Result.success(page);
    }

    /**
     * 获取所有供应商（不分页）
     */
    @GetMapping("/listAll")
    @ResponseBody
    public Result listAllSuppliers() {
        List<Supplier> suppliers = supplierService.getAllSuppliers();
        return Result.success(suppliers);
    }

    /**
     * 获取供应商详情
     */
    @GetMapping("/{supplierId}")
    @ResponseBody
    public Result getSupplierInfo(@PathVariable Integer supplierId) {
        Supplier supplier = supplierService.getSupplierById(supplierId);
        if (supplier != null) {
            return Result.success(supplier);
        } else {
            return Result.error("供应商不存在");
        }
    }

    /**
     * 添加供应商
     */
    @PostMapping("/add")
    @ResponseBody
    public Result addSupplier(@Validated @RequestBody Supplier supplier, Errors errors) {
        // 表单验证
        Map<String, Object> errorMap = validateSupplier(errors);
        if (!errorMap.isEmpty()) {
            return Result.error(errorMap, "表单验证失败");
        }

        // 检查供应商编码是否已存在
        if (supplierService.checkSupplierCodeExists(supplier.getSupplierCode(), null)) {
            return Result.error("供应商编码已存在");
        }

        // 检查供应商名称是否已存在
        if (supplierService.checkSupplierNameExists(supplier.getSupplierName(), null)) {
            return Result.error("供应商名称已存在");
        }

        // 保存供应商
        if (supplierService.addSupplier(supplier)) {
            return Result.success();
        } else {
            return Result.error();
        }
    }

    /**
     * 更新供应商
     */
    @PutMapping("/update")
    @ResponseBody
    public Result updateSupplier(@Validated @RequestBody Supplier supplier, Errors errors) {
        // 表单验证
        Map<String, Object> errorMap = validateSupplier(errors);
        if (!errorMap.isEmpty()) {
            return Result.error(errorMap, "表单验证失败");
        }

        // 检查供应商ID是否存在
        if (supplier.getSupplierId() == null) {
            return Result.error("供应商ID不能为空");
        }

        // 检查供应商是否存在
        Supplier existSupplier = supplierService.getSupplierById(supplier.getSupplierId());
        if (existSupplier == null) {
            return Result.error("供应商不存在");
        }

        // 检查供应商编码是否已存在（排除自身）
        if (supplierService.checkSupplierCodeExists(supplier.getSupplierCode(), supplier.getSupplierId())) {
            return Result.error("供应商编码已存在");
        }

        // 检查供应商名称是否已存在（排除自身）
        if (supplierService.checkSupplierNameExists(supplier.getSupplierName(), supplier.getSupplierId())) {
            return Result.error("供应商名称已存在");
        }

        // 更新供应商
        if (supplierService.updateSupplier(supplier)) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 删除供应商
     */
    @DeleteMapping("/delete/{supplierId}")
    @ResponseBody
    public Result deleteSupplier(@PathVariable Integer supplierId) {
        // 检查供应商是否存在
        Supplier supplier = supplierService.getSupplierById(supplierId);
        if (supplier == null) {
            return Result.error("供应商不存在");
        }

        // 删除供应商
        if (supplierService.deleteSupplier(supplierId)) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 批量删除供应商
     */
    @DeleteMapping("/batchDelete")
    @ResponseBody
    public Result batchDeleteSuppliers(@RequestBody Integer[] supplierIds) {
        if (supplierIds == null || supplierIds.length == 0) {
            return Result.error("请选择要删除的供应商");
        }

        // 批量删除
        if (supplierService.deleteSupplierBatch(supplierIds)) {
            return Result.success("批量删除成功");
        } else {
            return Result.error("批量删除失败");
        }
    }

    /**
     * 更新供应商评分
     */
    @PutMapping("/score")
    public Result updateSupplierScore(@RequestBody Supplier supplier) {
        if (supplier.getSupplierId() == null) {
            return Result.error("供应商ID不能为空");
        }

        // 更新评分
        supplierService.updateSupplierScore(supplier.getSupplierId());
        return Result.success();
    }

    /**
     * 获取供应商评级
     */
    @GetMapping("/level/{supplierId}")
    public Result getSupplierLevel(@PathVariable("supplierId") Integer supplierId) {
        Supplier supplier = supplierService.getSupplierById(supplierId);
        if (supplier == null) {
            return Result.error("供应商不存在");
        }

        String level = supplierService.determineSupplierLevel(supplier);
        return Result.success(level);
    }

    /**
     * 导入商品
     */
    @PostMapping("/import")
    @ResponseBody
    public Result importSupplier(@RequestParam(value = "file") MultipartFile file) {
        return importData(file, "supplier");
    }

    /**
     * 验证供应商表单
     */
    private Map<String, Object> validateSupplier(Errors errors) {
        Map<String, Object> errorMap = new HashMap<>();
        List<FieldError> fieldErrors = errors.getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return errorMap;
    }
}
